//
//  REAlbumViewController.m
//  录音
//
//  Created by ywy on 2016/12/26.
//  Copyright © 2016年 Wely. All rights reserved.
//

#import "REAlbumViewController.h"
#import "REdateTableViewCell.h"// cell
#import "ReRecordModel.h"
#import "RESingleton.h"
#import <MJRefresh/MJRefresh.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import <AVFoundation/AVFoundation.h>
#import "REfirstCategory.h"
#import "REClassifyLocalFileViewController.h"
#import "RECheckLogin.h"
#import "REThirdClassification.h"
//#import "RESelectAlbumViewController.h"
#import "RESelectAlbumLocalViewController.h"
struct PlayItemInfo{
    float total;
    float currentTime;
};

@interface REAlbumViewController ()<UITableViewDataSource,UITableViewDelegate,AVAudioPlayerDelegate,UIAlertViewDelegate>
{
      REfirstCategory * _firstCategory;
}

@property(nonatomic,strong) NSMutableArray * dateArr;
@property (nonatomic,strong)ReRecordModel * recordModel;
@property(nonatomic,strong) REdateTableViewCell * baseCell;
@property (nonatomic, strong) NSIndexPath *indexPath;

@property (nonatomic, strong) AVPlayer     *selfPlayer;
@property (nonatomic, assign) CMTime currentTime;
@property(nonatomic,assign) BOOL ispaly;
@property (nonatomic,assign) CGFloat progress;
@property (nonatomic,copy) NSString * progressStr;

@property (nonatomic, strong) id timeObserver;



@property(nonatomic,strong) ReRecordModel * baseMode;

@end


@implementation REAlbumViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(upDateTheDatabseClick) name:@"updateTheDatabase" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reFreshClicK:)  name:@"reFresh" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopPlayNoti)  name:@"stopPlay" object:nil];
       [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopPlayNotiFirsrt) name:@"stopPlayFirst" object:nil];
        if (self.dateArr.count) {
            [self.dateArr removeAllObjects];
        }
        NSArray * arr  = [[RESingleton defaultCent] readModelWithAlbum:self.titlelabel.text];
        self.dateArr = [NSMutableArray new];
        for (ReRecordModel* model in arr) {
            [self.dateArr addObject:model];
        }
    
     [self.baseTableVIew.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Update) name:@"Update" object:nil];
    self.ispaly = NO;
    self.indexPath = nil;
    self.headView.layer.borderColor = [UIColor redColor].CGColor;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    [self.headView addGestureRecognizer:tap];
    self.titlelabel.font = [UIFont fontWithName:@"MyriadPro-BoldCond" size:20];
      _firstCategory = [[REfirstCategory alloc] initWithFrame:CGRectMake(0, 0, REScreenW, REScreenH)];
    _firstCategory.hidden = YES;
    [_firstCategory.deleteButton addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
    [_firstCategory.popButton addTarget:self action:@selector(popClick) forControlEvents:UIControlEventTouchUpInside];
    [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:_firstCategory];
    self.baseTableVIew.delegate = self;
    self.baseTableVIew.dataSource = self;
    self.baseTableVIew.separatorStyle = 0;
    UIView * footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, REScreenW, 60)];
    self.baseTableVIew.tableFooterView =footView;
    [self.baseTableVIew registerNib:[UINib nibWithNibName:@"REdateTableViewCell" bundle:nil] forCellReuseIdentifier:@"REdateTableViewCell"];
    self.baseTableVIew.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if (self.dateArr.count) {
                [self.dateArr removeAllObjects];
            }
            NSArray * arr  = [[RESingleton defaultCent] readModelWithAlbum:self.titlelabel.text];
            self.dateArr = [NSMutableArray new];
            for (ReRecordModel* model in arr) {
                [self.dateArr addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.baseTableVIew reloadData];
                [self.baseTableVIew.mj_header endRefreshing];
            });
        });
    }];
    [self.baseTableVIew.mj_header beginRefreshing];
}

-(void)Update
{
    if (self.dateArr.count) {
        [self.dateArr removeAllObjects];
    }
    NSArray * arr  = [[RESingleton defaultCent] readModelWithAlbum:self.titlelabel.text];
    self.dateArr = [NSMutableArray new];
    for (ReRecordModel* model in arr) {
        [self.dateArr addObject:model];
    }
    
    [self.baseTableVIew.mj_header beginRefreshing];
    
}


-(void)tapClick
{
    __weak typeof(self) weakSelf = self;
    RESelectAlbumLocalViewController * selectLocalAlbumVC = [[RESelectAlbumLocalViewController alloc] init];
    selectLocalAlbumVC.albumBlockTwo = ^(REThirdClassification * model)
    {
        if (weakSelf.dateArr.count) {
            [weakSelf.dateArr removeAllObjects];
        }
        weakSelf.titlelabel.text = model.thirdTypeName;
        NSArray * arr  = [[RESingleton defaultCent] readModelWithAlbum:model.thirdTypeName];
        for (ReRecordModel* model in arr) {
            [self.dateArr addObject:model];
        }
        [self.baseTableVIew reloadData];
    };
    
    [self.navigationController pushViewController:selectLocalAlbumVC animated:YES];

}

-(void)reFreshClicK:(NSNotification*)notification
{
    NSLog(@"%@ === %@ === %@", notification.object, notification.userInfo, notification.name);
    
    NSDictionary * dict = notification.userInfo;
    
    if ([dict[@"number"] isEqualToString:@"1"]) {
        
        [self.baseTableVIew .mj_header beginRefreshing];
    }
    
}

-(void)deleteClick
{
    _firstCategory.hidden = YES;
}
-(void)popClick
{
    _firstCategory.hidden = YES;
    // 归类
    REClassifyLocalFileViewController * classifyLocalVC =[[REClassifyLocalFileViewController alloc] init];
    classifyLocalVC.baseModel = self.recordModel;
    [self.navigationController pushViewController:classifyLocalVC animated:YES];
    
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dateArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        __weak typeof(self) weakSelf = self;
    REdateTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"REdateTableViewCell"];
    ReRecordModel * mdeol = self.dateArr[indexPath.row];
    cell.indexPath  = indexPath;
    [cell showDate:mdeol withIndexPath:_indexPath];
    if (![self.indexPath isEqual:indexPath]){
        cell.progressView.progress = 0;
        cell.progressLabel.text = @"00:00";
    }else{
        cell.progressView.progress = self.progress;
        cell.progressLabel.text = self.progressStr ? self.progressStr  : @"00:00";
    }
    cell.palyButton.selected = [self.indexPath isEqual:indexPath] && self.ispaly;


    cell.play = ^(ReRecordModel * baseModel,BOOL playOrStop,NSInteger number,UITableViewCell * baseCell,NSIndexPath*indexPathOfBlcok)
    {
        
        switch (number) {
            case 10001:
            {
                YPLog(@"选中的cell %@",indexPathOfBlcok);
                //                _indexPath = indexPathOfBlock;
                weakSelf.baseCell = [weakSelf.baseTableVIew cellForRowAtIndexPath:_indexPath];
                [weakSelf palyAndStop:playOrStop withModel:baseModel andIndexPath:indexPath seleCted:_indexPath];
            }
                break;

        case 10002:
            {
                UIAlertView * titleAlert = [[UIAlertView alloc] initWithTitle:@"客官不要啊！！" message:@"客官确定要删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                weakSelf.baseMode = baseModel;
                [titleAlert show];
            }
                break;
            case 10003:
            {
                if (![baseModel.isUpPost isEqualToString:@"noUp"]) {
                    [SVProgressHUD showErrorWithStatus:@"曲目已上传"];
                    return;
                }else
                {
                    // 上传
                    if (![baseModel.isClas isEqualToString:@"noClass"]) {
                        // 已经归类 开始上传
                        [weakSelf postFilewith:baseModel];
                    }else
                    {
                        _firstCategory.hidden = NO;
                        weakSelf.recordModel = baseModel;
                    }
                }
            }
                break;
            case 10004:
            {
                // 归类
              
                REClassifyLocalFileViewController * classifyLocalVC =[[REClassifyLocalFileViewController alloc] init];
                 classifyLocalVC.noclassStr = baseModel.isClas;
                classifyLocalVC.baseModel = baseModel;
                [weakSelf.navigationController pushViewController:classifyLocalVC animated:YES];
            }
                break;
            default:
                break;
        }
    };
    cell.selectionStyle = 0;
    return cell;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        //删除
        BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath: [RECheckLogin getlocalPath:@"/" allStr:self.baseMode.baseUrl]];
        if (!blHave) {
            [SVProgressHUD showErrorWithStatus:@"文件不存在"];
            return ;
        }else {
            
            BOOL blDele= [[NSFileManager defaultManager] removeItemAtPath:[RECheckLogin getlocalPath:@"/" allStr:self.baseMode.baseUrl]  error:nil];
            if (blDele) {
                [SVProgressHUD showSuccessWithStatus:@"文件删除成功!!!!"];
                [[RESingleton defaultCent] deleteModel:self.baseMode.baseUrl];
                [self.baseTableVIew.mj_header beginRefreshing];
            }else {
                [SVProgressHUD showErrorWithStatus:@"文件删除失败!!!!"];
            }
        }
        
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}

-(void)postFilewith:(ReRecordModel*)model
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary * dict = [NSMutableDictionary new];
    dict[@"cmd"] = @"uploadMusic";
    dict[@"uid"] = [UserDefaults objectForKey:@"userid"];
    dict[@"firstTypeId"] = model.firstStr;
    dict[@"secondTypeId"] = model.secondStr;
    dict[@"thirdTypeId"] = model.thirdStr;
    dict[@"albumLength"] = model.currentTime;
    dict[@"albumName"] = model.titleStr;
    NSString * filename = [NSString stringWithFormat:@"%@.caf",[RECheckLogin stringFromDateTwo:[NSDate date]]];
    dict[@"file"] = filename;
    dict[@"localId"] = model.baseUrl;
    
    [SVProgressHUD showWithStatus:@"曲目上传中...."];
    [RECheckLogin POSTTwo:REBaseUrl parameters:dict withFormData:^(id form) {
        
        [form appendPartWithFileURL:[NSURL fileURLWithPath:[RECheckLogin getlocalPath:@"/" allStr:model.baseUrl]] name:@"file" fileName:filename mimeType:@"file" error:nil];
        
    } progress:^(CGFloat prosser) {
        
    } success:^(id responseObject) {
        if ([responseObject[@"result"] isEqualToString:@"0"]) {
            [SVProgressHUD showSuccessWithStatus:@"曲目上传成功"];
              [[NSNotificationCenter defaultCenter] postNotificationName:@"postSucces" object:nil];
            // 已经上传的 时候 需要更新数据库的信息
            if (  [[RESingleton defaultCent] isUp:model.baseUrl] == YES && [[RESingleton defaultCent] isIdStr:responseObject[@"mid"] with:model.baseUrl]) {
                [weakSelf .baseTableVIew.mj_header beginRefreshing];
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"更新数据失败!!!!"];
            }
            
        }else
        {
//            [SVProgressHUD showErrorWithStatus:@"上传曲目失败"];
        }
          [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:@"网络加载失败!!!"];
    }];
}


//- (void)stopPlayWithIndex:(NSIndexPath *)index withFlag:(BOOL)flag{
//    
//    if (_indexPath && _indexPath != index && flag) {
//        REdateTableViewCell *cell = [self.baseTableVIew cellForRowAtIndexPath:_indexPath];
//        [cell.palyButton setSelected:NO];
//        [cell stopPlay];
//    }
// 
//    
//    
//    _indexPath = index;
//    
//}
-(void)palyAndStop:(BOOL)playOrStop  withModel:(ReRecordModel*)baseModel andIndexPath:(NSIndexPath*)indexPath seleCted:(NSIndexPath*)indexPathOfBlock
{
    if (![self.indexPath isEqual:indexPath]){
        [self initPalyerWithModel:baseModel];
    }else{
        if (!self.ispaly) {
            REdateTableViewCell * cell = [self.baseTableVIew cellForRowAtIndexPath:indexPath];
            if (cell.progressView.progress <= 0) {
                [self.selfPlayer seekToTime:CMTimeMake(0, 1)];
            }
            [self.selfPlayer play];
            
            self.ispaly = YES;
        }else{
            [self.selfPlayer pause];
            self.ispaly = NO;
        }
    }
    
    self.indexPath = indexPath;
    [self.baseTableVIew reloadData];
    
}
-(void)initPalyerWithModel:(ReRecordModel*)baseModel{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [self.selfPlayer.currentItem removeObserver:self  forKeyPath:@"status"];
    [self.selfPlayer removeTimeObserver:self.timeObserver];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    NSURL *localURL = [NSURL fileURLWithPath:[RECheckLogin getlocalPath:@"/" allStr:baseModel.baseUrl]];
    AVURLAsset *localAssert = [[AVURLAsset alloc]initWithURL:localURL options:nil];
    //AVPlayerItem 他是对assert对应资源的一种整体描述，包括能够播放，以及影片长度等内容
    AVPlayerItem * item = [[AVPlayerItem alloc]initWithAsset:localAssert];
    
    
    //使用item生成player，这里会对影片进行预加载分析，然后更新item的状态
    //            self.selfPlayer.volume = 1;
    
    if(self.selfPlayer){
        [self.selfPlayer pause];
        self.selfPlayer = nil;
    }
    self.selfPlayer = [AVPlayer playerWithPlayerItem:item];
    //监听AVPlayerItem的status状态，当status状态为readyToPlayer时，我们认为影片时可以播放的
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:self.selfPlayer.currentItem];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    __weak typeof(self) weakSelf = self;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem*)object;
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            //这里影片可以播放
            [self.selfPlayer play];
            self.ispaly = YES;
         weakSelf.timeObserver =  [weakSelf.selfPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                //time是指当前影片播放的时间
                //得到影片的总时间
                CMTime totalTime = weakSelf.selfPlayer.currentItem.duration;
                //CMTimeGetSeconds 把CMTime转换为秒数
                CGFloat currentTimeSeconds = CMTimeGetSeconds(time);
                CGFloat totalSeconds = CMTimeGetSeconds(totalTime);
                int  minnute = currentTimeSeconds/60;
                int second = currentTimeSeconds-minnute*60;
                REdateTableViewCell * cell = [weakSelf.baseTableVIew cellForRowAtIndexPath:weakSelf.indexPath];
                weakSelf.progressStr = [NSString stringWithFormat:@"%02d:%02d",minnute,second];
                weakSelf.progress = currentTimeSeconds*1.0/totalSeconds;
                if (cell){
                    cell.progressLabel.text = weakSelf.progressStr;
                    [cell.progressView setProgress:weakSelf.progress animated:NO];
                }
            }];
            [self.baseTableVIew reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:@"录音文件暂时无法播放"];
        }
    }
}
-(void)playbackFinished{
    REdateTableViewCell * cell = [self.baseTableVIew cellForRowAtIndexPath:self.indexPath];
    if (cell){
        cell.progressView.progress = 0.0;
        cell.progressLabel.text = @"00:00";
        self.progress = 0.0;
        self.progressStr = @"00:00";
        [cell.palyButton setSelected:NO];
    }
    self.ispaly = NO;
}



-(void)upDateTheDatabseClick
{
    [self.baseTableVIew.mj_header beginRefreshing];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateTheDatabase" object:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)pushClick:(UIButton *)sender {
    
    __weak typeof(self) weakSelf = self;
    RESelectAlbumLocalViewController * selectLocalAlbumVC = [[RESelectAlbumLocalViewController alloc] init];
    selectLocalAlbumVC.albumBlockTwo = ^(REThirdClassification * model)
    {
        if (weakSelf.dateArr.count) {
            [weakSelf.dateArr removeAllObjects];
        }
        weakSelf.titlelabel.text = model.thirdTypeName;
        NSArray * arr  = [[RESingleton defaultCent] readModelWithAlbum:model.thirdTypeName];
        for (ReRecordModel* model in arr) {
            [self.dateArr addObject:model];
        }
        [self.baseTableVIew reloadData];
    };
    
    [self.navigationController pushViewController:selectLocalAlbumVC animated:YES];

}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.selfPlayer) {
        REdateTableViewCell * cell = [self.baseTableVIew cellForRowAtIndexPath:self.indexPath];
        self.ispaly = NO;
        [cell.palyButton setSelected:NO];
        [self.selfPlayer pause];
    }

//    self.selfPlayer = nil;
}
-(void)stopPlayNoti
{
    if (self.selfPlayer) {
        REdateTableViewCell * cell = [self.baseTableVIew cellForRowAtIndexPath:self.indexPath];
        self.ispaly = NO;
        [cell.palyButton setSelected:NO];
        [self.selfPlayer pause];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"stopPlayNoti" object:nil];
}
-(void)stopPlayNotiFirsrt
{
    if (self.selfPlayer) {
        REdateTableViewCell * cell = [self.baseTableVIew cellForRowAtIndexPath:self.indexPath];
        self.ispaly = NO;
        [cell.palyButton setSelected:NO];
        [self.selfPlayer pause];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"stopPlayNotiFirsrt" object:nil];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
